package com.work.work.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.work.work.common.R;
import com.work.work.dto.ProjectCreateDTO;
import com.work.work.dto.ProjectDTO;
import com.work.work.dto.ProjectOverviewDTO;
import com.work.work.entity.Project;
import com.work.work.service.ProjectService;
import com.work.work.service.TaskService;
import com.work.work.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@Tag(name = "项目管理")
@RestController
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;
    @Autowired
    private UserService userService;

    @Autowired
    private TaskService taskService;
    @Operation(summary = "分页获取项目列表")
    @GetMapping("/page")
    public R<Page<ProjectDTO>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        // 创建 MyBatis-Plus 分页对象，默认统计总数
        Page<ProjectDTO> page = new Page<>(current, size);

        // 调用 Service 实现分页查询
        Page<ProjectDTO> resultPage = projectService.pageWithTeamName(page);

        // 更新每个项目的进度数据
        for (ProjectDTO project : resultPage.getRecords()) {
            projectService.updateProjectProgress(project.getId());
        }
        long total = resultPage.getTotal(); // 获取总记录数
        if (total == 0) {
            // 防止 total 为 0 的情况（可追踪为空或统计有问题时设置默认总数）
            total = projectService.countTotalProjects(); // 针对统计问题直接重新查询总记录数
            resultPage.setTotal(total); // 手动赋值
        }

        // 确定总页数
        long totalPages = (total + size - 1) / size;
        resultPage.setPages(totalPages);

        // 返回分页结果
        return R.ok(resultPage, "查询成功");
    }

    @Operation(summary = "按项目名称搜索")
    @GetMapping("/search")
    public R<Page<ProjectDTO>> searchByName(
            @RequestParam String projectName,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {

        // 创建分页对象
        Page<ProjectDTO> page = new Page<>(current, size);

        // 获取搜索结果
        Page<ProjectDTO> result = projectService.searchByProjectName(projectName, page);

        // 更新每个项目的进度
        for (ProjectDTO project : result.getRecords()) {
            taskService.updateProjectProgress(project.getId());
        }

        // 重新查询更新后的数据
        result = projectService.searchByProjectName(projectName, page);

        return R.ok(result, "查询成功");
    }
    @Operation(summary = "更新项目")
    @PutMapping("/update")
    public R<Boolean> updateProject(@RequestBody Project project) {
        // 验证必填字段
        if (project.getId() == null) {
            return R.fail("项目ID不能为空");
        }
        if (project.getProjectName() == null || project.getProjectName().trim().isEmpty()) {
            return R.fail("项目名称不能为空");
        }
        if (project.getStartTime() == null) {
            return R.fail("开始时间不能为空");
        }
        if (project.getTeamId() == null) {
            return R.fail("团队ID不能为空");
        }

        try {
            // 检查项目是否存在
            Project existingProject = projectService.getById(project.getId());
            if (existingProject == null) {
                return R.fail("项目不存在");
            }
            // 更新项目
            boolean success = projectService.updateById(project);
            return success ?
                R.ok(true, "项目更新成功") :
                R.fail("项目更新失败");
        } catch (Exception e) {
            log.error("更新项目失败", e);
            return R.fail("更新项目失败：" + e.getMessage());
        }
    }
    @Operation(summary = "根据ID获取项目")
    @GetMapping("/{id}")
    public R<Project> getById(@PathVariable Integer id) {
        Project project = projectService.getById(id);
        return project != null ? R.ok(project, "项目创建成功") : R.fail("项目不存在");
    }
  @Operation(summary = "获取项目总览数据")
    @GetMapping("/overview")
    public R<ProjectOverviewDTO> getProjectOverview() {
        ProjectOverviewDTO overview = new ProjectOverviewDTO();

        // 获取项目总数
        long projectCount = projectService.count();
        overview.setTotalProjects(projectCount);

        // 获取资金总额（从资源表中获取）
        Double totalBudget = projectService.sumTotalBudget();
        overview.setTotalBudget(totalBudget);

        // 获取人力总数（从资源表中获取）
        Integer totalManpower = projectService.sumTotalManpower();
        overview.setTotalManpower(totalManpower);

        // 获取任务总数
        long taskCount = taskService.count();
        overview.setTotalTasks(taskCount);

        return R.ok(overview, "获取成功");
    }
//    @Operation(summary = "创建新项目")
//    @PostMapping("/create")
//    public R<Project> createProject(@RequestBody CreateProjectRequest request) {
//        Project project = new Project();
//        BeanUtils.copyProperties(request, project);
//
//        if (projectService.createProject(project)) {
//            return R.ok(project);
//        }
//        return R.fail("创建项目失败");
//    }
@Operation(summary = "创建项目")
@PostMapping("/create")
public R<Project> createProject(@RequestBody ProjectCreateDTO projectDTO) {
    // 验证必填字段
    if (projectDTO.getProjectName() == null || projectDTO.getProjectName().trim().isEmpty()) {
        return R.fail("项目名称不能为空");
    }
    if (projectDTO.getStartTime() == null) {
        return R.fail("开始时间不能为空");
    }
    if (projectDTO.getTeamId() == null) {
        return R.fail("团队ID不能为空");
    }
    if (projectDTO.getResourceAllocations() == null || projectDTO.getResourceAllocations().isEmpty()) {
        return R.fail("至少需要分配一个资源");
    }

    return projectService.createProject(projectDTO) ?
            R.ok(null, "项目创建成功") :
            R.fail("项目创建失败");
}
    @Operation(summary = "更新项目")
    @PutMapping
    public R<Boolean> update(@RequestBody Project project) {
        return projectService.updateById(project) ? R.ok(true, "项目创建成功") : R.fail("更新项目失败");
    }

    @Operation(summary = "删除项目")
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Integer id) {
        return projectService.deleteProject(id) ?
                R.ok(true, "删除项目成功") :
                R.fail("删除项目失败");
    }
    @Operation(summary = "导出项目进度报表")
    @GetMapping("/report/export")
    public void exportProjectReport(HttpServletResponse response) {
        try {
            projectService.generateProjectReport(response);
        } catch (IOException e) {
            log.error("导出报表失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}